package com.qf.chinatrip.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import com.qf.chinatrip.view.AlbumPagerItemView;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Fcy on 2015/3/23.
 */
public class AlbumPagerAdapter extends PagerAdapter {
    private List<String> imgUrls;
    private Context context;

    /**
     * HashMap保存相片的位置以及ItemView.
     */
    private HashMap<Integer, AlbumPagerItemView> map;

    public AlbumPagerAdapter(List<String> imgUrls, Context context) {
        this.imgUrls = imgUrls;
        this.context = context;
        map = new HashMap<Integer, AlbumPagerItemView>();
    }

    @Override

    public int getCount() {
        return imgUrls.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object o) {
        return view == o;
    }

    /**
     * 回收
     *
     * @param container
     * @param position
     * @param object
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (object instanceof AlbumPagerItemView) {
            AlbumPagerItemView view = (AlbumPagerItemView) object;
            view.recycle();
        }
    }

    /**
     * 添加视图
     *
     * @param container
     * @param position
     * @return
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        AlbumPagerItemView itemView;
        if (map.containsKey(position)) {
            itemView = map.get(position);
            itemView.reload();
        } else {
            itemView = new AlbumPagerItemView(context);
            itemView.setData(imgUrls.get(position));
            map.put(position, itemView);
            ((ViewPager) container).addView(itemView);
        }

        return itemView;
    }
}
